package com.situ.controller;

import com.alipay.api.AlipayApiException;
import com.situ.context.BaseContext;
import com.situ.domain.entity.TOrder;
import com.situ.ex.PayException;
import com.situ.service.OrderService;
import com.situ.util.AliPayUtil;
import com.situ.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/alipay")
@RequiredArgsConstructor
@Tag(name = "支付宝接口")
public class AlliPayController {

    private final AliPayUtil aliPayUtil;

    private final OrderService orderService;



    @GetMapping(value = "/pay")
    @Operation(summary = "支付宝支付")
    public Result<String> payMoney (String oid, Double totalPrice) {
        TOrder order = TOrder.builder()
                .oid(oid)
                .totalPrice(totalPrice)
                .uid(BaseContext.getCurrentId())
                .build();
        try {
            return Result.success(200, "等待支付", aliPayUtil.pay(order));
        } catch (AlipayApiException e) {
            throw new PayException(e);
        }
    }

    @RequestMapping("/callback")
    @Operation(summary = "支付宝回调")
    public String callback(HttpServletRequest request) {
        System.out.println("支付宝异步回调了方法callback");
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> keySet = parameterMap.keySet();
        Map<String,String> map=new HashMap<>();
        for (String key : keySet) {
            map.put(key,request.getParameter(key));
        }
        for (Map.Entry<String, String> me : map.entrySet()) {
            System.out.println(me.getKey()+"="+me.getValue());
        }
        Integer uid = Integer.parseInt(map.get("subject"));
        String oid = map.get("body");
        orderService.payedOrder(uid,oid);
        return "success";
    }

}
